#include "CalculatorWindow.h"
#include <QApplication>
#include <QStyle>
#include <QFile>

CalculatorWindow::CalculatorWindow(QWidget *parent)
    : QWidget(parent), m_display(new QLineEdit)
{
    // 设置显示区域为只读，用户只能通过按钮进行输入
    m_display->setReadOnly(true);
    m_display->setAlignment(Qt::AlignRight);

    // 初始化网格布局
    QGridLayout *layout = new QGridLayout;

    // 将显示区域添加到布局
    layout->addWidget(m_display, 0, 0, 1, 4);

    // 创建按钮并将它们添加到布局
    const QString buttons[4][4] = {
        {"7", "8", "9", "/"},
        {"4", "5", "6", "*"},
        {"1", "2", "3", "-"},
        {"C", "0", "=", "+"}
    };
    for (int i = 0; i < 4; ++i) {
        for (int j = 0; j < 4; ++j) {
            QPushButton *button = createButton(buttons[i][j]);
            layout->addWidget(button, i + 1, j);
        }
    }

    // 设置布局
    setLayout(layout);

    // 设置窗口标题
    setWindowTitle(tr("Calculator"));

    // 加载QSS样式
    QFile file(":/resources/style.qss");
    file.open(QFile::ReadOnly);
    QString styleSheet = QLatin1String(file.readAll());
    qApp->setStyleSheet(styleSheet);
}

CalculatorWindow::~CalculatorWindow()
{
    delete m_display;
}

QPushButton *CalculatorWindow::createButton(const QString &text)
{
    QPushButton *button = new QPushButton(text);
    connect(button, &QPushButton::clicked, this, &CalculatorWindow::onButtonClicked);
    return button;
}

void CalculatorWindow::onButtonClicked()
{
    QPushButton *clickedButton = qobject_cast<QPushButton *>(sender());
    QString buttonText = clickedButton->text();

    if (buttonText == "C") {
        m_display->clear();
    } else if (buttonText == "=") {
        QString expression = m_display->text();
        QString result = m_evaluator.evaluate(expression);
        m_display->setText(expression + " = " + result);
    } else {
        m_display->setText(m_display->text() + buttonText);
    }
}

